package com.design_patterns.chain_of_responsibility.version;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-28 21:05
 **/
public class ServletMain3 {

    public static void main(String[] args) {
        Request request = new Request();
        request.setStr(" 干坏事 <script> location.href='www.xxxx.com' </script> 说坏话：工作 996 ");
        Response response = new Response();
        response.setStr("response");

        FilterChain chain = new FilterChain();
        chain.add(new HTMLFilter()).add(new SensitiveFilter());
        chain.doFilter(request, response);
        System.err.println(request.str);
        System.err.println(response.str);

    }
}

interface Filter {
    void doFilter(Request request, Response response, FilterChain chain);
}

class HTMLFilter implements Filter {
    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        request.str = request.str.replaceAll("<", "[").replaceAll(">", "]") + "HTMLFilter()";
        chain.doFilter(request, response);
        response.str += "--HTMLFilter()";
    }
}

class Request {
    String str;

    public void setStr(String str) {
        this.str = str;
    }
}

class Response {
    String str;

    public void setStr(String str) {
        this.str = str;
    }
}

class SensitiveFilter implements Filter {
    @Override
    public void doFilter(Request request, Response response, FilterChain chain) {
        request.str = request.str.replaceAll("996", "955") + " SensitiveFilter()";
        chain.doFilter(request, response);
        response.str += "--SensitiveFilter()";
    }
}

class FilterChain {
    List<Filter> filters = new ArrayList<>();
    int index = 0;

    public FilterChain add(Filter f) {
        filters.add(f);
        return this;
    }

    public void doFilter(Request request, Response response) {
        if (index == filters.size())
            return;
        Filter f = filters.get(index);
        index++;
        f.doFilter(request, response, this);
    }
}
